/***********************************************************************************
Copy right:     Coffee Tech.
Author:         jiaoyue
Date:           2019.11.21
Description:    测试msg_peer组件
***********************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <msg_queue_peer.h>
#include "cJSON.h"
#include "modbus.h"
#define errDbug printf("%s %d\n", __func__, __LINE__)
struct msgbuf
{
    long mtype;
    char mdata[256];
};

int main(int argc, char *argv[])
{
    struct msgbuf recv_buf;

    modbus_t *ctx = modbus_new_tcp("192.168.0.119", 7777);
    if (ctx == NULL)
    {
        errDbug;
        return -1;
    }
    if (modbus_set_slave(ctx, 1) < 0)
    {
        errDbug;
        return -1;
    }
    if (modbus_connect(ctx) < 0)
    {
        errDbug;
        return -1;
    }
    modbus_t *ctx_air = ctx;
    modbus_t *ctx_light = ctx;
    modbus_t *ctx_r = ctx;
    while (1)
    {
        if (msg_queue_recv("msg", &recv_buf, sizeof(recv_buf), 0, 0) > 0)//接收
        {
            if (recv_buf.mtype == 2)
            {
                cJSON *root = NULL;
                cJSON *modbus = NULL;
                modbus = cJSON_Parse(recv_buf.mdata);
                if (!modbus)
                {
                    perror("modbus err");
                    return -1;
                }
                //modbus = cJSON_GetObjectItem(root, "modbus");
                int key = cJSON_GetObjectItem(modbus, "key")->valueint;
				//判断
                if(key == 103)
                {
                    int val = atoi(cJSON_GetObjectItem(modbus, "val")->valuestring);
                    printf("103 val:%d\n",val);
                    modbus_write_bit(ctx_air, 0, val);
                }
                if(key == 104)
                {
                    double val = atof(cJSON_GetObjectItem(modbus, "val")->valuestring);
                    modbus_write_register(ctx_r, 0, val);
                }
                if(key == 105)
                {
                    int val = atoi(cJSON_GetObjectItem(modbus, "val")->valuestring);
                    modbus_write_bit(ctx_light, 1, val);
                }
                printf("recv from msga type = %ld\n", recv_buf.mtype);
                printf("recv from msga data = %s\n", recv_buf.mdata);
            }
        }
        else
        {
            perror("recv error:");
            break;
        }

    }
    pause();

    return 0;
}
